<template>
  <div class="message-detail" :style="{ minHeight: minHeight + 'px' }">
    <div class="chat-room">
      <div
        class="chat-desk"
        :style="{ height: deskHeight + 'px' }"
        ref="chatDesk"
      >
        <div class="pannel" ref="pannel">
          <div
            v-for="(item, index) in chattingRecords"
            :key="index"
            :class="[
              item.isSelfStyleBox ? 'selfStyleBox' : 'otherStyleBox',
              'baseStyle'
            ]"
          >
            <div class="user-avatar">
              <img :src="item.avatar" alt="" v-if="item.avatar" />
                <div class="svg" v-else>
                    <svg  t="1587545175014" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10677" width="32" height="32">
                        <path d="M0 512a512 512 0 1 0 1024 0 512 512 0 0 0-1024 0z" fill="#7FC2FF" p-id="10678"></path>
                        <path d="M840.594286 850.797714A463.542857 463.542857 0 0 1 511.707429 987.428571 463.542857 463.542857 0 0 1 182.857143 850.797714v-299.264C182.857143 368.128 330.093714 219.428571 511.707429 219.428571c181.650286 0 328.886857 148.699429 328.886857 332.068572 0.731429 173.092571 0.731429 272.859429 0 299.300571z" fill="#EBF9FF" p-id="10679"></path>
                        <path d="M329.142857 457.142857a54.857143 54.857143 0 1 0 109.714286 0 54.857143 54.857143 0 0 0-109.714286 0zM585.142857 457.142857a54.857143 54.857143 0 1 0 109.714286 0 54.857143 54.857143 0 0 0-109.714286 0zM402.285714 585.142857a109.714286 109.714286 0 0 0 219.428572 0" fill="#66B5FF" p-id="10680"></path></svg>
                </div>
            </div>
            <div class="chat-detail">
              <div class="user-chatTime">
                <span
                  class="chat-time"
                  v-text="cleanDate(item.createTime)"
                ></span>
              </div>
              <div class="bubbles content" v-text="item.message"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-bar">
        <van-field
          v-model="message"
          center
          autosize
          type="textarea"
          maxlength="120"
          rows="1"
          ref="field"
          :placeholder="this.$t('placeHolder.sendMessage')"
        >
          <van-button
            slot="button"
            size="small"
            type="info"
            :disabled="!message.length"
            @click="sendMessage"
          >
            {{ $t("send") }}
          </van-button>
        </van-field>
      </div>
    </div>
  </div>
</template>

<script>
import { Button, Field } from 'vant';
import 'vant/lib/field/style/less';

export default {
    name: 'message-detail',
    data () {
        return {
            friendAvtar: undefined,
            friendId: undefined,
            storageRoom: null,
            minHeight: 0,
            deskHeight: 0,
            message: '',
            isNewFriend: false,
            orderId: undefined,
            chattingRecords: []
        };
    },
    components: {
        [Button.name]: Button,
        [Field.name]: Field
    },
    created () {
    // 获取与对方的聊天记录， 判断orderId, friendId
        this.friendId = this.$route.params.chatId;
        this.orderId = this.$route.params.orderId;
        if (!this.friendId) {
            this.$router.replace('/');
        } else {
            this.$api.messageApi
                .resetAllUnReadMessageStatus({
                    orderId: this.orderId,
                    friendId: localStorage.getItem('id')
                })
                .then(res => {
                    console.log(res);
                })
                .catch();
            const setUserParams = {
                method: 'get',
                url: '/api/v1/profile/',
                params: { id: this.friendId }
            };
            const setMessageParams = {
                method: 'get',
                url: 'api/v1/message',
                params: {
                    orderId: this.orderId,
                    myId: localStorage.getItem('id')
                }
            };
            this.$api.otherApi
                .axiosAll(setUserParams, setMessageParams)
                .then(result => {
                    if (result[0].code === 2010) {
                        this.friendAvtar = result[0].data.avatar;
                        this.$store.commit('simpleAssignment', {
                            state: 'title',
                            value: result[0].data.nickname
                        });
                        if (result[1].code !== 4024 && result[1].code !== 2023) {
                            this.$util.failToast(
                                `${result[1].message},错误代码${result[1].code}`
                            );
                        } else {
                            if (result[1].data.length) {
                                this.cleanData(result[1].data);
                            }
                        }
                    } else {
                        this.$util.failToast(result[0].message);
                    }
                })
                .catch();
        }
    },
    mounted () {
        this.minHeight = this.$util.ScreenCanUseHeight();
        this.deskHeight = this.$util.ScreenCanUseHeight(60);
        this.$socket.emit('joinRoom', {
            self: this.$store.state.userInfo._id,
            friend: this.friendId,
            orderId: this.orderId
        });
    },
    destroyed () {
    // 离开房间
        this.$socket.emit('leaveRoom', this.$store.state.userInfo._id);
    },
    methods: {
        sendMessage () {
            this.$socket.emit('sendToServer', {
                messageData: {
                    userId: this.$store.state.userInfo._id,
                    friendId: this.friendId,
                    message: this.message,
                    createTime: new Date(),
                    order: this.orderId
                },
                roomId: this.storageRoom
            });
            this.message = '';
        },
        drawChatBubbles (message) {
            const globalStyle = message.userId === this.$store.state.userInfo._id;
            this.chattingRecords.push(
                Object.assign(
                    {
                        isSelfStyleBox: globalStyle,
                        avatar: globalStyle
                            ? this.$store.state.userInfo.avatar
                            : this.friendAvtar
                    },
                    message
                )
            );
        },
        cleanDate (time) {
            return this.$moment(time).format('M月DD日 HH:mm');
        },
        cleanData (messageRecordArray) {
            _.forEach(messageRecordArray, value => {
                // 别人发送过来的信息放左边
                const globalStyle = value.userId !== this.friendId;
                this.chattingRecords.push(
                    Object.assign(
                        {
                            isSelfStyleBox: globalStyle,
                            avatar: globalStyle
                                ? this.$store.state.userInfo.avatar
                                : this.friendAvtar
                        },
                        value
                    )
                );
            });
        }
    },
    sockets: {
        reconnect () {
            this.$socket.emit('joinRoom', {
                self: this.$store.state.userInfo._id,
                friend: this.friendId,
                orderId: this.orderId
            });
        },
        broadcast (data) {
            this.drawChatBubbles(data);
        },
        returnRoomId (roomId) {
            this.storageRoom = roomId;
        }
    },
    watch: {
        chattingRecords: function () {
            this.$nextTick(function () {
                if (this.deskHeight < this.$refs.pannel.clientHeight) {
                    this.$refs.chatDesk.scrollTop =
            this.$refs.pannel.clientHeight - this.deskHeight;
                }
            });
        }
    }
};
</script>

<style scoped lang="less" src="./less/message-detail.less"></style>
